import json
import requests
import re


class SparkModel:
    def __init__(self):
        self.api_key = "Bearer vPtAkGiZkaHSMqmBPrLp:etgmxfiXIPaNntICqMrw"
        self.url = "https://spark-api-open.xf-yun.com/v2/chat/completions"
        self.chat_history = []

    def remove_emoji(self, text):
        """
        移除 Unicode 表情符号（如⭐️、😊等）
        """
        emoji_pattern = re.compile(
            "["
            "\U0001F600-\U0001F64F"  # emoticons
            "\U0001F300-\U0001F5FF"  # symbols & pictographs
            "\U0001F680-\U0001F6FF"  # transport & map symbols
            "\U0001F700-\U0001F77F"  # alchemical symbols
            "\U0001F780-\U0001F7FF"  # Geometric Shapes Extended
            "\U0001F800-\U0001F8FF"  # Supplemental Symbols and Pictographs
            "\U0001F900-\U0001F9FF"  # Supplemental Symbols and Pictographs
            "\U0001FA00-\U0001FA6F"  # Chess Symbols
            "\U0001FA70-\U0001FAFF"  # Symbols and Pictographs Extended-A
            "\U00002702-\U000027B0"  # Dingbats
            "]+",
            flags=re.UNICODE
        )
        return emoji_pattern.sub(r'', text)

    def get_answer(self, message):
        """
        向星火模型发送请求并获取完整回答（非逐行）
        """
        headers = {
            'Authorization': self.api_key,
            'content-type': "application/json"
        }
        body = {
            "model": "x1",
            "user": "user_id",
            "messages": message,
            "stream": True,
            "tools": [
                {
                    "type": "web_search",
                    "web_search": {
                        "enable": True,
                        "search_mode": "deep"
                    }
                }
            ]
        }

        full_response = ""

        response = requests.post(url=self.url, json=body, headers=headers, stream=True)

        for chunks in response.iter_lines():
            if chunks and '[DONE]' not in str(chunks):
                data_org = chunks[6:]
                try:
                    chunk = json.loads(data_org)
                except json.JSONDecodeError:
                    continue

                text = chunk['choices'][0]['delta']

                if 'content' in text and text['content']:
                    content = text["content"]
                    content = content.replace('*', '').replace('#', '').replace('-', '')
                    content = re.sub(r'\n\s*\n', '\n', content).strip()
                    content = self.remove_emoji(content)

                    if content:
                        full_response += content + "\n"

        return full_response.strip()

    def get_text(self, role, content):
        """
        添加对话记录到 chat_history
        """
        self.chat_history.append({
            "role": role,
            "content": content
        })
        return self.chat_history

    def get_length(self):
        """
        获取当前对话总长度
        """
        return sum(len(msg["content"]) for msg in self.chat_history)

    def check_length(self):
        """
        如果超过限制则清理历史记录
        """
        while self.get_length() > 11000:
            self.chat_history.pop(0)
        return self.chat_history

    def main(self, fx, bs, jl, ms):
        """
        主函数：根据输入生成总统评价
        """
        Input = f'我面试的方向为{fx}，其中笔试成绩为{bs}分，简历成绩为{jl}分，面试成绩为{ms}分，请给出总统评价'
        self.check_length()
        self.get_text("user", Input)
        response = self.get_answer(self.chat_history)
        self.get_text("assistant", response)
        # 返回无换行版本内容
        return response.strip().replace('\n', ' ').replace('  ', ' ')

#
# if __name__ == '__main__':
#     spark = SparkModel()
#     result = spark.main('数据库', 56, 80, 80)
#     if result:
#         print(result)
#     else:
#         print("未找到模型输出内容")
